import pymysql


conn = pymysql.Connect(
    host = 'localhost',
    port = 3306,
    user = 'root',
    passwd = '123456',
    charset='utf8',
    database='users_db'
)

def con_my_sql(sql_code):
    try:
        conn.ping(reconnect=True)
        print(sql_code)

        # 通过游标对象对数据库服务器发出sql语句
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute(sql_code)

        # 提交
        conn.commit()
        # 关闭连接
        conn.close()
        # 普通执行返回1，就是执行成功
        return cursor
    except pymysql.MySQLError as err_massage:
        # 回滚
        conn.rollback()
        # 关闭连接
        conn.close()
        # 返回错误类型
        return type(err_massage), err_massage